extends Node
enum Bus{MASTER,BGM,SFX}
@onready var sfx: Node = $SFX
@onready var bgm: Node = $BGM
@onready var bgm_player: AudioStreamPlayer2D = $BGM/DefaultBGM

@export_file("*.ogg") var default_bgm_music:String = ""
@onready var default_bgm: AudioStream

var sfx_sounds : Dictionary

func _ready():
	for child in sfx.get_children():
		var name:String = child.name
		name = name.to_lower()
		sfx_sounds[name] = child
		
	if default_bgm_music != "":
		default_bgm = load(default_bgm_music)
	
func play_sfx(name:String,is_repeat:bool=true) -> void:
	var sfx:AudioStreamPlayer = get_play_sfx(name)
	if sfx == null:
		return
		
	if is_repeat:
		sfx.play()
	else:
		if not sfx.is_playing():
			sfx.play()
	
func get_play_sfx(name) -> AudioStreamPlayer:
	var sfxv:Variant = sfx_sounds.get(name,null)
	if sfxv == null:
		return null
	var sfx:AudioStreamPlayer = sfxv as AudioStreamPlayer
	if sfx == null:
		return null
	return sfx
		
func setup_ui_sounds(node:Node) -> void:
	var button := node as Button
	if button:
		button.pressed.connect(player_ui_pressed)
		button.focus_entered.connect(player_ui_focus)
		button.mouse_entered.connect(button.grab_focus)
	else:
		var slider := node as Slider
		if slider:
			slider.value_changed.connect(player_ui_pressed.unbind(1))
			slider.focus_entered.connect(player_ui_focus)
			slider.mouse_entered.connect(slider.grab_focus)
	
	for child in node.get_children():
		setup_ui_sounds(child)
		
func player_ui_pressed() -> void:
	print("uipressed")
	play_sfx("uipressed",false)

func player_ui_focus() -> void:
	play_sfx("uifocus",false)

func play_bgm(stream:AudioStream) -> void:
	if bgm_player.stream == stream && bgm_player.is_playing():
		return
		
	bgm_player.stream = stream
	bgm_player.play()

func play_default_bgm() -> void:
	if default_bgm != null:
		play_bgm(default_bgm)

func get_volume(bus_index: int) -> float:
	var db:=AudioServer.get_bus_volume_db(bus_index)
	return db_to_linear(db)

func set_volume(bus_index: int, v:float) -> void:
	var db:= linear_to_db(v)
	AudioServer.set_bus_volume_db(bus_index, db)
 
